package cn.ycxy.lbl.member.controller;

import cn.ycxy.lbl.common.exception.BusinessException;
import cn.ycxy.lbl.common.exception.enums.ResponseEnum;
import cn.ycxy.lbl.common.pojo.CsAuthenticationInfo;
import cn.ycxy.lbl.common.restful.R;
import cn.ycxy.lbl.member.service.IUserService;
import cn.ycxy.lbl.member.utils.LoginUtils;
import cn.ycxy.lbl.member.utils.SecurityContextUtils;
import cn.ycxy.lbl.pojo.member.domain.User;
import cn.ycxy.lbl.pojo.member.dto.UserInfoModifyDTO;
import cn.ycxy.lbl.pojo.member.dto.UserLoginDTO;
import cn.ycxy.lbl.pojo.member.vo.LoginSuccessVO;
import cn.ycxy.lbl.pojo.member.vo.UserApproveDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/user/info")
public class UserInfoController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "用户身份信息认证更新")
    @PostMapping("/modify")
    public R<Void> modify(@Valid @RequestBody UserInfoModifyDTO userInfoModifyDTO){
        Long userId = SecurityContextUtils.getUserId();
        User user = new User();
        user.setId(userId);
        //认证中
        user.setApproveStatus(1);
        BeanUtils.copyProperties(userInfoModifyDTO, user);
        if (!userService.updateById(user)) {
            throw new BusinessException(ResponseEnum.UPDATE_ERROR);
        }
        return R.ok();
    }

    @ApiOperation(value = "获取用户身份认证信息")
    @GetMapping ("/get")
    public R<UserApproveDetailVO> getUserApprove(){
        Long userId = SecurityContextUtils.getUserId();
        UserApproveDetailVO vo = new UserApproveDetailVO();
        vo.setIdentity(-1);
        User user = userService.getById(userId);
        BeanUtils.copyProperties(user, vo);
        return R.ok(vo);
    }

    @ApiOperation(value = "更新用户身份")
    @PostMapping ("/loadToken")
    public R<String> loadToken(){
        CsAuthenticationInfo userInfo = SecurityContextUtils.getUserInfo();
        //已请求更新过token, 不需要再更新
        if (userInfo.getAuthorities().contains("ROLE_user")) {
            return R.ok("");
        }
        return R.ok(userService.loadTokenByUser());
    }
}
